/*
 * @lc app=leetcode.cn id=2134 lang=cpp
 *
 * [2134] 最少交换次数来组合所有的 1 II
 */

// @lc code=start
class Solution
{
public:
    int minSwaps(vector<int> &nums)
    {
        int len = 0;
        for (int x : nums)
        {
            if (x == 1)
            {

                len++;
            }
        }

        int zeros = 0;
        for (int i = 0; i < len; i++)
        {
            if (nums[i] == 0)
            {
                zeros++;
            }
        }

        int l = 0, r = len - 1, n = nums.size();
        int ans = INT_MAX;
        for (int i = 0; i < n; i++)
        {
            ans = min(ans, zeros);
            if (nums[l] == 0)
            {
                zeros--;
            }
            if (nums[(r + 1) % n] == 0)
            {
                zeros++;
            }
            l++, r++;
        }

        return ans;
    }
};
// @lc code=end
